module.exports = {
	checkToken: checkToken,

	wxlogin: wxlogin,
	bindPhone: bindPhone,
	login: login,

	addWxEwjMsg: addWxEwjMsg,
	addWxEwjMsgs:addWxEwjMsgs,
	
	findWxEwjMsgById: findWxEwjMsgById,

	uploadFile: uploadFile,

	findAllWxInfo: findAllWxInfo,
	addWxInfo: addWxInfo,
	putWxInfo: putWxInfo,
	delWxInfo: delWxInfo,


	findWxRemind: findWxRemind,
	addWxRemind: addWxRemind,
	putWxRemind: putWxRemind,
	delWxRemind: delWxRemind,


	getCode: getCode,

	findAllInfos: findAllInfos,
	addFriend: addFriend,
	updInfo: updInfo,
	delFriend: delFriend,






}

var app = getApp()


var apiHost = "https://emp.empsun.com";
// var apiHost = "https://empsun.empsun.com";


// 登录地址, 根据这个地址来设置token
var logInUrl = "/Account/LogInForMiniProgram";
// 例外不用token的地址
var exceptionAddrArr = [
	'http://localhost:8080',
	'/s-ewq/api/v3/wx/getToken'
];




//登录接口，给与回调，同步执行代码
function wxlogin(eData, iv) {
	return new Promise(function(resolve, reject) {
		wx.login({
			success: res => {
				// 获取到用户的 code 之后：res.code
				console.log("用户的code====>>>" + res.code);
				// 可以传给后台，再经过解析获取用户的 openid
				// 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
				wx.request({
					// 自行补上自己的 APPID 和 SECRET
					// url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
					url: apiHost + '/s-xcx/api/v3/wx/wxLogin?type=EWJ&code=' + URLencode(res.code) + '&eData=' + URLencode(eData) +
						'&iv=' +URLencode(iv),

					success: res => {
						console.log(res)
						// 获取到用户的 openid
						console.log("用户的openid:" + res.data.data.openid);

						app.globalData.head.openid = res.data.data.openid
						app.globalData.head.token = 'no'

						console.log(app.globalData)
						console.log(app.globalData.tokenkey)

						//请求成功回调
						resolve(res.data.data)


					},
					fail(err) {
						console.log(err)
						console.log('请求调用失败')
						//请求失败回调
						reject(err)

					},
					complete: function(data) {
						checkStatus(data)
					}


				});
			},
			fail(err) {
				console.log(err)
				console.log('获取code失败')

			}
		});
	})

}

//将用户授权后获取到的手机号上传到服务器并绑定到openid
function bindPhone(e, success, fail) {
	console.log('===========调用绑定手机号api')
	return postRequest('/s-xcx/api/v3/wx/bindPhone', e, function(res) {
		success(res)
	}, function(err) {
		fail(err)
	})
}

function login(callback) {

	return getRequest('/s-xcx/api/v3/wx/login?openid=' + app.globalData.head.openid, function(res) {
		console.log('====>>res:')
		console.log(res)
		app.globalData.head.token = res.data.data.token
		app.globalData.head.noToken = false
		app.globalData.users = res.data.data.infos

		findWxRemind()

		callback && typeof callback === 'function' ? callback(res) : null;

	}, function(err) {
		console.log('====>>err:')
		console.log(err)
		callback && typeof callback === 'function' ? callback(err) : null;
	})
}
//查询记录
function findWxEwjMsgById(userId) {

	return getRequest('/s-xcx/api/v3/ewj/findWxEwjMsgById?userId=' + userId + '&cels=' + app.globalData.cels, function(
		res) {
		console.log('====>>查询记录res:')
		console.log(res)

		app.globalData.userdatas = res.data.data


	}, function(err) {
		console.log('====>>查询记录err:')
		console.log(err)
	})
}
//添加记录
function addWxEwjMsg(data) {

	return postRequest('/s-xcx/api/v3/ewj/addWxEwjMsg', data, function(res) {
		console.log('====>>添加记录res:')
		console.log(res)
	}, function(err) {
		console.log('====>>添加记录err:')
		console.log(err)
	})
}
//批量添加记录
function addWxEwjMsgs(datas) {

	return postRequest('/s-xcx/api/v3/ewj/addWxEwjMsgs', datas, function(res) {
		console.log('====>>添加记录res:')
		console.log(res)
	}, function(err) {
		console.log('====>>添加记录err:')
		console.log(err)
	})
}
function uploadFile(filePath, callback) {
	let uri = '/s-file/api/file/uploads'

	CreateHeader(uri, function(header) {
		wx.uploadFile({
			url: apiHost + uri,
			filePath: filePath,
			name: 'multipartFile',
			header: header,

			success(res) {
				console.log(res.data)
				console.log(JSON.parse(res.data).data)
				let url = JSON.parse(res.data).data.fileUrl
				console.log(url)
				//do something
				callback && typeof callback === 'function' ? callback(url) : null;
			}
		})
	})

}
//========微信用户start
function findAllWxInfo(callback) {
	getRequest('/s-xcx/api/v3/ex/info/findAllWxInfo', function(res) {
		console.log('====>>微信用户 查询结果')
		console.log(res)
		app.globalData.users = res.data.data
		callback && typeof callback === 'function' ? callback(false) : null;
	}, function(err) {

		callback && typeof callback === 'function' ? callback(true) : null;
	})
}

function addWxInfo(data, callback) {

	postRequest('/s-xcx/api/v3/ex/info/addWxInfo', data, function(res) {
		callback && typeof callback === 'function' ? callback(res) : null;

	}, function(err) {
		callback && typeof callback === 'function' ? callback(err) : null;

	})

}

function putWxInfo(data, callback) {

	putRequest('/s-xcx/api/v3/ex/info/putWxInfo', data, function(res) {
		callback && typeof callback === 'function' ? callback(res) : null;

	}, function(err) {
		callback && typeof callback === 'function' ? callback(err) : null;

	})

}

function delWxInfo(wxInfoId, callback) {
	delRequest('/s-xcx/api/v3/ex/info/delWxInfo?wxInfoId=' + wxInfoId, function(res) {

		callback && typeof callback === 'function' ? callback(false) : null;
	}, function(err) {

		callback && typeof callback === 'function' ? callback(true) : null;
	})
}

//============用户订阅 start

function findWxRemind(callback) {
	getRequest('/s-xcx/api/v3/ewj/findWxRemind', function(res) {
		console.log('====>>用户订阅 查询结果')
		console.log(res)
		app.globalData.wxRemind = res.data.data
		callback && typeof callback === 'function' ? callback(false) : null;
	}, function(err) {

		callback && typeof callback === 'function' ? callback(true) : null;
	})
}

function addWxRemind(data, callback) {

	postRequest('/s-xcx/api/v3/ewj/addWxRemind', data, function(res) {
		callback && typeof callback === 'function' ? callback(res) : null;

	}, function(err) {
		callback && typeof callback === 'function' ? callback(err) : null;

	})

}

function putWxRemind(data, callback) {

	putRequest('/s-xcx/api/v3/ewj/putWxRemind', data, function(res) {
		callback && typeof callback === 'function' ? callback(res) : null;

	}, function(err) {
		callback && typeof callback === 'function' ? callback(err) : null;

	})

}

function delWxRemind(callback) {
	delRequest('/s-xcx/api/v3/ewj/delWxRemind', function(res) {

		callback && typeof callback === 'function' ? callback(false) : null;
	}, function(err) {

		callback && typeof callback === 'function' ? callback(true) : null;
	})
}






//===========================================公用方法===========================

function checkToken() {

	return !app.globalData.head.noToken;
}

/** 
 * @param url:String  require(必需) 请求地址相对路径
 * @param data:Object   可选  请求数据
 * @param success:Function  可选   成功回调函数
 * @param fail:Function     可选    失败回调函数
 */
function getRequest(uri, success, fail) {
	CreateHeader(uri, function(header) {
		wx.request({
			url: apiHost + uri,
			method: 'GET',

			header: header,
			success: function(res) {

				if (success && typeof success === "function") {
					success(res);
				}
			},
			fail: function(error) {
				if (fail && typeof fail === "function") {
					fail(error);
				} else {
					console.log(error);
				}
			},
			complete: function(data) {
				checkStatus(data)
			}
		})
	});
}

function delRequest(uri, success, fail) {
	CreateHeader(uri, function(header) {
		wx.request({
			url: apiHost + uri,
			method: 'DELETE',

			header: header,
			success: function(res) {

				if (success && typeof success === "function") {
					success(res);
				}
			},
			fail: function(error) {
				if (fail && typeof fail === "function") {
					fail(error);
				} else {
					console.log(error);
				}
			},
			complete: function(data) {
				checkStatus(data)
			}
		})
	});
}
/** 
 * @param url:String  require(必需) 请求地址相对路径
 * @param data:Object   可选  请求数据
 * @param success:Function  可选   成功回调函数
 * @param fail:Function     可选    失败回调函数
 */
function postRequest(uri, data, success, fail) {
	CreateHeader(uri, function(header) {

		console.log(header)
		wx.request({
			url: apiHost + uri,
			method: 'POST',
			data: data,
			header: header,
			success: function(res) {
				console.log('POST请求成功')

				if (success && typeof success === "function") {
					success(res);
				}
			},
			fail: function(error) {
				console.log('POST请求失败')

				if (fail && typeof fail === "function") {
					fail(error);
				} else {
					console.log(error);
				}
			},
			complete: function(data) {
				checkStatus(data)
			}
		})
	})

}

function putRequest(uri, data, success, fail) {
	CreateHeader(uri, function(header) {

		console.log(header)
		wx.request({
			url: apiHost + uri,
			method: 'PUT',
			data: data,
			header: header,
			success: function(res) {
				console.log('PUT 请求成功')


				if (success && typeof success === "function") {
					success(res);
				}
			},
			fail: function(error) {
				console.log('PUT 请求失败')

				if (fail && typeof fail === "function") {
					fail(error);
				} else {
					console.log(error);
				}
			},
			complete: function(data) {
				checkStatus(data)
			}
		})
	})

}

/** 
 * @param url:String    请求地址(根据请求地址判断是否添加token)
 * @param callback:Function 回调函数
 */
function CreateHeader(uri, callback) {
	var header = {
		'content-type': 'application/json'
	}
	if (exceptionAddrArr.indexOf(uri) == -1) { //排除请求的地址不需要token的地址
		header.openid = app.globalData.head.openid;
		header.token = app.globalData.head.token
		console.log('====header')
		console.log(header)
		callback && typeof callback === 'function' ? callback(header) : null;

		// wx.getStorage({
		// 	key: app.globalData.tokenkey,
		// 	success: function(res) {
		// 		console.log('====================================+++++++++++++++++++++++++++++++')
		// 		console.log(res)
		// 		header.openid = res.data.openid;
		// 		header.token = res.data.token

		// 	},
		// 	fail: function(error) {
		// 		console.log(error);
		// 	},
		// 	complete: function() {
		// 		console.log('====header')
		// 		console.log(header)
		// 		callback && typeof callback === 'function' ? callback(header) : null;
		// 	}
		// });
	} else {
		callback && typeof callback === 'function' ? callback(header) : null;
	}
}

/**
 * @param {Object} sStr
 * 对字符串编码
 */
function URLencode(sStr) {
	return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
}
let t_num = 0
let e_num = 0

function checkStatus(res) {
	console.log('====>>checkStatus')
	// console.log(res)
	if (res.data.code == 401) {
		console.log('====>>token过期')
		app.globalData.head.token = ''
		if (t_num < 2) {
			t_num++
			wx.showModal({
				title: '身份认证过期,点击确定重新登录',
				showCancel: false,
				success(res) {
					if (res.confirm) {
						console.log('====>>token过期，用户点击确定')
						login()
						t_num--
					} else if (res.cancel) {
						console.log('====>>token过期，用户点击取消')
					}

				}
			})
		}
	} else if (res.statusCode >= 500 && res.statusCode < 600) {
		wx.showModal({
			title: '服务异常',
			showCancel: false,
			success(res) {
				if (res.confirm) {
					console.log('====>>服务器异常，用户点击确定')
				} else if (res.cancel) {
					console.log('====>>服务器异常，用户点击取消')
				}
			}
		})
	}
}

// ======================新增========================
function getCode(phone) {
	let userName = 'A' + phone
	let uri = '/s-user/api/v2/user/getCode?userName=' + userName

	return new Promise(function (resolve, reject) {
		get(uri).then(res => {
			resolve(true)
		}).catch(err => {
			reject(false)
		})
	})

}


function getHeader(uri) {
	var header = {
		'content-type': 'application/json'
	}
	if (exceptionAddrArr.indexOf(uri) == -1) { //排除请求的地址不需要token的地址
		// header.openid = app.globalData.head.openid;
		header.token = app.globalData.head.token

	}
	return new Promise(function (resolve, reject) {
		console.log('====header')
		console.log(header)
		resolve(header)
	})

}


function get(uri) {
	console.log('==>>GET 请求参数')
	console.log(uri)

	return new Promise(function (resolve, reject) {
		getHeader(uri).then(res => {
			wx.pro.request({
				url: apiHost + uri,
				method: 'GET',
				header: res,
			}).then(res => {
				console.log('==>>GET res:' + res)
				console.log(res)
				checkStatus(res)
				resolve(res)
			}).catch(err => {
				console.log('==>>GET err:' + err)
				reject(err)
			}).finally(() => {
				console.log('==>>GET:final:' + uri)
			})
		})
	})

}

function post(uri, data) {
	console.log('==>>POST 请求参数')
	console.log(data)

	return new Promise(function (resolve, reject) {
		getHeader(uri).then(res => {
			wx.pro.request({
				url: apiHost + uri,
				method: 'POST',
				data: data,
				header: res,
			}).then(res => {
				console.log('==>>POST res:' + res)
				checkStatus(res)
				resolve(res)
			}).catch(err => {
				console.log('==>>POST err:' + err)
				reject(err)
			}).finally(() => {
				console.log('==>>POST:final:' + uri)
			})
		})
	})

}

function put(uri, data) {
	console.log('==>>PUT 请求参数')
	console.log(data)


	return new Promise(function (resolve, reject) {
		getHeader(uri).then(res => {
			wx.pro.request({
				url: apiHost + uri,
				method: 'PUT',
				data: data,
				header: res,
			}).then(res => {
				console.log('==>>PUT res:' + res)
				checkStatus(res)
				resolve(res)
			}).catch(err => {
				console.log('==>>PUT err:' + err)
				reject(err)
			}).finally(() => {
				console.log('==>>PUT:final:' + uri)
			})
		})
	})


}


function del(uri) {
	console.log('==>>DELETE 请求参数')
	console.log(uri)


	return new Promise(function (resolve, reject) {
		getHeader(uri).then(res => {
			wx.pro.request({
				url: apiHost + uri,
				method: 'DELETE',
				header: res,
			}).then(res => {
				console.log('==>>DELETE res:' + res)
				checkStatus(res)
				resolve(res)
			}).catch(err => {
				console.log('==>>DELETE err:' + err)
				reject(err)
			}).finally(() => {
				console.log('==>>DELETE:final:' + uri)
			})
		})
	})


}


function findAllInfos() {
	let uri = '/s-xcx/api/v3/ex/info/findAllInfos'
	return new Promise(function (resolve, reject) {
		get(uri).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

function addFriend(data) {
	let uri = '/s-xcx/api/v3/ex/info/bindFriend'
	return new Promise(function (resolve, reject) {
		post(uri, data).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

function updInfo(data) {
	let uri = '/s-xcx/api/v3/ex/info/updInfo'
	return new Promise(function (resolve, reject) {
		put(uri, data).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

function delFriend(friendId) {
	let uri = '/s-xcx/api/v3/ex/info/delFriend?friendId=' + friendId
	return new Promise(function (resolve, reject) {
		del(uri).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}
